<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateUserMeetingAPIRequest;
use App\Http\Requests\API\UpdateUserMeetingAPIRequest;
use App\Http\Services\UserMeetingDTOBuilderService;
use App\Http\Services\WeixinAuth;
use App\Models\Meeting;
use App\Models\UserMeeting;
use App\Repositories\UserMeetingRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use App\Http\Modules\MicroMsgFactory;
use Response;
use QrCode;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;

/**
 * Class UserMeetingController
 * @package App\Http\Controllers\API
 */
class UserMeetingAPIController extends AppBaseController
{
    /** @var  UserMeetingRepository */
    private $userMeetingRepository;

    /**
     * Display a listing of the UserMeeting.
     * GET|HEAD /userMeetings
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->userMeetingRepository->pushCriteria(new RequestCriteria($request));
        $this->userMeetingRepository->pushCriteria(new LimitOffsetCriteria($request));
        $userMeetings = $this->userMeetingRepository->all();

        return $this->sendResponse($userMeetings->toArray(), 'User Meetings retrieved successfully');
    }

    /**
     * display_order asc
     * @param TicketModelRepository $repo
     */
    public function search(UserMeetingRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['status'] = [0, 1];
        $input = $this->request->all();
        $code = array_get($input, 'code', 0);
        !empty($code) && $searchOptions['code'] = $code;

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        $lists = UserMeetingDTOBuilderService::buildMeeting($lists);
        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * export 导出excel
     * @param UserMeetingRepository $repo
     * @return \Illuminate\Http\JsonResponse
     */
    public function export(UserMeetingRepository $repo)
    {
        $str = '';
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $sortOptions['all'] = 1;

        $searchOptions['status'] = [0, 1];
        $input = $this->request->all();
        $type = array_get($input, 'type', 0);
        !empty($type) && $searchOptions['type'] = $type;

        $meetingId = array_get($input, 'meeting_id', 0);
        !empty($meetingId) && $searchOptions['meeting_id'] = $meetingId;
        !empty($meetingId) && $str = "{$meetingId}_";

        $ret = $repo->search($searchOptions, $sortOptions);

        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->error(1, "无数据,无需导出");
        }

        if ($type == 10) {
            $filename = '/storage/'. $str .'baoming.xlsx';
        } elseif ($type == 11) {
            $filename = '/storage/' . $str . 'canzhan.xlsx';
        } else {
            $filename = '/storage/' . $str . 'all_user.xlsx';
        }

        $url = UserMeetingDTOBuilderService::export($lists, $filename);

        return response($url)->header('Content-Type', 'text/html');
    }

    /**
     * 使用userId
     * @param TicketModelRepository $repo
     */
    public function apiSearch(UserMeetingRepository $repo)
    {
        $searchOptions = $this->normalizeSearchOptions();
        $sortOptions = $this->normalizeSortOptions();
        $searchOptions['user_id'] = $this->request->attributes->get('user_id');
        $searchOptions['status'] = [0, 1];

        $ret = $repo->search($searchOptions, $sortOptions);
        $lists = $ret['lists'];
        if (count($lists) == 0) {
            return $this->success(['lists' => []]);
        }

        $lists = UserMeetingDTOBuilderService::buildMeeting($lists);
        $ret['lists'] = $lists;

        return $this->success($ret);
    }

    /**
     * Store a newly created UserMeeting in storage.
     * POST /userMeetings
     *
     * @param CreateUserMeetingAPIRequest $request
     *
     * @return Response
     */
    public function store(UserMeetingRepository $userMeetingRepository, WeixinAuth $auth)
    {
        $input = $this->request->all();
        $userId = $this->request->attributes->get('user_id');
        $user = $this->request->attributes->get('user');
        $formId = $input['form_id'] ?? "";
        $this->validateInputParams('store', $input);
        // 验证是否已经报名
//        $um = UserMeeting::where(['user_id' => $userId, 'meeting_id' => $input['meeting_id']])->whereIn('status', [0, 1])->first();
//        if (!empty($um)) {
//            return $this->error(1, "您已报名");
//        }

        $meeting = Meeting::where('id', $input['meeting_id'])->first();
        if (empty($meeting)) {
            return $this->error(1, "会议不存在");
        }

        $input['code'] = date("YmdHis") . mt_rand(10, 99);
        $input['user_id'] = $userId;

        // 生成barcode;
        $str = 'barcode_' . $input['code'] . '.png';
        $barcode = $this->generateBarcodeAndUpload($input['code'], $str);
        $input['barcode'] = $barcode;
        $userMeetings = $userMeetingRepository->create($input);

        $msg = MicroMsgFactory::generate($input['type']);
        $msg->buildData($meeting, $input);
        $auth->pushMicroMsg($user->open_id, $formId, $msg);

        return $this->sendResponse($userMeetings->toArray(), 'User Meeting saved successfully');
    }

    /**
     * @param $code
     * @param string
     */
    private function generateBarcodeAndUpload($code, $str, $deleteQrcode = true)
    {
        QrCode::format('png')->encoding('UTF-8')->size(1000)->margin(1)->generate($code, public_path("storage/" . $str));

        $accessKey = config('customer.qiniu_ak');
        $secretKey = config('customer.qiniu_sk');
        $bucket = config('customer.qiniu_bucket');

        $auth = new Auth($accessKey, $secretKey);
        $token =  $auth->uploadToken($bucket);
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $str, public_path("storage/" . $str));
        $deleteQrcode && unlink(public_path("storage/" . $str));

        return QINIU_DOMAIN . "{$str}";
    }

    /**
     * admin 接口,核销ticket
     * @param UserTicketRepository $repo
     */
    public function applyTicket($id, UserMeetingRepository $repo)
    {
//        $code = $this->request->get('code');
//        if (empty($code)) {
//            throwResponseException(1, '券码为空');
//        }

        $userTicket = UserMeeting::where('id', $id)->first();
        if (empty($userTicket)) {
            return $this->error(1, '券码不存在');
        }

        if ($userTicket->status != 0) {
            return $this->error(1, '已核销');
        }

        $userTicket->status = 1;

        $userTicket->save();

        return $this->success();
    }

    /**
     * Display the specified UserMeeting.
     * GET|HEAD /userMeetings/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id, UserMeetingRepository $userMeetingRepository)
    {
        /** @var UserMeeting $userMeeting */
        $userMeeting = $userMeetingRepository->findWithoutFail($id);

        if (empty($userMeeting)) {
            return $this->sendError('User Meeting not found');
        }

        return $this->sendResponse($userMeeting->toArray(), 'User Meeting retrieved successfully');
    }

    /**
     * Update the specified UserMeeting in storage.
     * PUT/PATCH /userMeetings/{id}
     *
     * @param  int $id
     * @param UpdateUserMeetingAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateUserMeetingAPIRequest $request)
    {
        $input = $request->all();

        /** @var UserMeeting $userMeeting */
        $userMeeting = $this->userMeetingRepository->findWithoutFail($id);

        if (empty($userMeeting)) {
            return $this->sendError('User Meeting not found');
        }

        $userMeeting = $this->userMeetingRepository->update($input, $id);

        return $this->sendResponse($userMeeting->toArray(), 'UserMeeting updated successfully');
    }

    /**
     * Update the specified UserMeeting in storage.
     * PUT/PATCH /userMeetings/{id}
     *
     * @param  int $id
     * @param UpdateUserMeetingAPIRequest $request
     *
     * @return Response
     */
    public function updatePosting($id, UserMeetingRepository $userMeetingRepository)
    {
        /** @var UserMeeting $userMeeting */
        $userMeeting = $userMeetingRepository->findWithoutFail($id);

        if (empty($userMeeting)) {
            return $this->sendError('User Meeting not found');
        }

        $image = $this->request->file('upload_file', null);
        if (empty($image)) {
            return $this->error(1, '图片不存在');
        }

        $key = "user_meeting_{$id}_" . mt_rand(1000, 9999) . "_" .$image->getClientOriginalName();

        $path = $image->storeAs("", $key);
        //list($ret, $err) = $this->uploadQiniu($image, $key);

        $str = 'barcode_' . $key;
        $code = env('APP_URL') . "/storage/" . $key;

        $barcode = $this->generateBarcodeAndUpload($code, $str);

        $arr = ['post_uri' => $code, 'barcode' => $barcode];
        $userMeeting = $userMeetingRepository->update($arr, $id);

        return $this->sendResponse($userMeeting->toArray(), 'UserMeeting updated successfully');
    }

    /**
     * Remove the specified UserMeeting from storage.
     * DELETE /userMeetings/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var UserMeeting $userMeeting */
        $userMeeting = $this->userMeetingRepository->findWithoutFail($id);

        if (empty($userMeeting)) {
            return $this->sendError('User Meeting not found');
        }

        $userMeeting->delete();

        return $this->sendResponse($id, 'User Meeting deleted successfully');
    }

    /**
     * 参数验证规则
     * self::VALID_RULES[__FUNCTION__]
     */
    const VALID_RULES = [
        'store' => [
            'meeting_id' => 'required|int|min:1',
            'job' => 'required|string',
            'type' => 'required|int|min:10|max:11',
            'name' => 'required|string',
            'mobile' => 'required|string',
            'packages' => 'string',
            'company' => 'required|string',
            'email' => 'required|string|email',
        ],
    ];
}
